package com.googlecode.scenemaker3d.controller
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.net.URLRequest;
	
	import com.googlecode.scenemaker3d.model.VO_material;
	import com.googlecode.scenemaker3d.model.World3DModel;

	public class MaterialController implements IMaterialController
	{
		private var mWorld:World3DModel;
		
		public function MaterialController(m:World3DModel)
		{
			mWorld = m;
		}

		public function addMaterial(filePath:String, type:String):void
		{
			var url:URLRequest = new URLRequest(filePath);

			switch(String(type))
			{
				case "swf":
					loadSWFsAndImages(url);					
					break;
				case "jpg":
					loadSWFsAndImages(url);
					break;
				case "jpeg":
					loadSWFsAndImages(url);
					break;
				case "gif":
					loadSWFsAndImages(url);
					break;
				case "png":
					loadSWFsAndImages(url);
					break;
				case "mp3":
					trace("mp3");
					break;
				case "flv":
					trace("flv");
					break;
				
			}
			
			mWorld.matID ++;
		}
		
		public function removeMaterial(id:String):void
		{
		}
		private function loadSWFsAndImages(url:URLRequest):void
		{
			var VO:VO_material = new VO_material();
			
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWForImageLoaded);
			
			loader.load(url);
		}
		private function onSWForImageLoaded(e:Event):void
		{
			if((e.target as LoaderInfo).contentType == null)
			{
				return;
			}
			
			var VO:VO_material = new VO_material();
			VO.type = (e.target as LoaderInfo).contentType;
			VO.filePath = (e.target as LoaderInfo).url;
			VO.content = (e.target as LoaderInfo).content;
			VO.originalWidth = (e.target as LoaderInfo).content.width;
			VO.originalHeight = (e.target as LoaderInfo).content.height;
			
			//Sort out media type
			switch((e.target as LoaderInfo).contentType)
			{
				case "application/x-shockwave-flash":
					VO.id = "SWF_" + mWorld.matID;
					break;
				case "image/jpeg":
					VO.id = "jpeg_" + mWorld.matID;
					break;
				case "image/gif":
					VO.id = "gif_" + mWorld.matID;
					break;
				case "image/png":
					VO.id = "png_" + mWorld.matID;
					break;
				
			}

			mWorld.materials.addItem(VO);
			mWorld.matID ++;
			trace(mWorld.materials);
		}
	}
}